package com.funmi.lizip.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.*;
import com.funmi.lizip.entity.Device;
import com.funmi.lizip.entity.DeviceData;
import com.funmi.lizip.entity.Image;
import com.funmi.lizip.entity.vo.ImageVo;
import com.funmi.lizip.mapper.DataMapper;
import com.funmi.lizip.mapper.ImageMapper;
import com.funmi.lizip.service.DataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funmi.lizip.service.DeviceService;
import com.funmi.lizip.service.ImageService;
import com.funmi.lizip.utils.FuzzyDetection;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzy
 * @since 2022-11-02
 */
@Service
public class DataServiceImpl extends ServiceImpl<DataMapper, DeviceData> implements DataService {


    @Autowired
    private DeviceService deviceService;

    @Autowired
    private ImageService imageService;


    @Autowired
    private DataMapper dataMapper;

    @Autowired
    private ImageMapper imageMapper;


    /**
     * 测报灯
     *
     * @param stringObjectHashMap
     * @return
     */
    @Override
    public R saveTelemeteringLamp(HashMap<String, Object> stringObjectHashMap) {
        //HashMap<String, Object> hashMap = new HashMap<>();

        // 转换成JSON字符串进行存储
        String s = JSONObject.toJSONString(stringObjectHashMap);
        DeviceData deviceData = new DeviceData();
        //
        //deviceData.setDeviceId(2);
//        s.  ext   .idccid
//        int sn = deviceService.getSn();
//         deviceData.setDeviceId(sn);


        // 修改

        deviceData.setUpdateAt(LocalDateTime.now());

        deviceData.setCreateAt(LocalDateTime.now());
        deviceData.setDelete(false);


        // 取出限定里的内容
        HashMap<String, Object> hashMap = JSON.parseObject(s, HashMap.class);
        Object payload = hashMap.get("payload");
        String s2 = payload.toString();

        HashMap<String, Object> hashMap2 = JSON.parseObject(s2, HashMap.class);
        Object ext = hashMap2.get("ext");
        // 取出etc 之后的内容
        String s1 = ext.toString();


        // 截取出imei
        HashMap hashMap1 = JSONObject.parseObject(s1, HashMap.class);
        Object objectImei = hashMap1.get("imei");

        // 设备ID
        Integer sn = deviceService.getSn(objectImei.toString());
        if (null == sn) {
            throw new RuntimeException("设备ID为空");
        }


        //deviceData.setDeviceId(2);
        deviceData.setDeviceId(sn);

        deviceData.setDeviceData(s1);

        boolean save = this.save(deviceData);
        if (save) {
            return R.success().data(deviceData).code(ResultCode.SUCCESS);
        } else {
            return R.fail().code(ResultCode.UNKNOWN);
        }
    }


    /**
     * 孢子仪
     *
     * @param stringObjectHashMap
     */
    @Override
    public R saveRobeInstrument(HashMap<String, Object> stringObjectHashMap) {
        // 转换成JSON字符串进行存储
        String s = JSONObject.toJSONString(stringObjectHashMap);
        DeviceData deviceData = new DeviceData();

        // 修改
        deviceData.setUpdateAt(LocalDateTime.now());
        deviceData.setCreateAt(LocalDateTime.now());
        deviceData.setDelete(false);

        HashMap<String, Object> hashMap = JSON.parseObject(s, HashMap.class);
        Object payload = hashMap.get("payload");
        String s2 = payload.toString();

        HashMap<String, Object> hashMap2 = JSON.parseObject(s2, HashMap.class);
        Object ext = hashMap2.get("ext");
        // 取出etc 之后的内容
        String s1 = ext.toString();


        // 截取出iccid
        HashMap hashMap1 = JSONObject.parseObject(s1, HashMap.class);
        Object objectImei = hashMap1.get("imei");
//        int iccid = Integer.parseInt(objectIccid.toString());
//
        Integer deviceId = deviceService.getSn(objectImei.toString());
        if (null == deviceId) {
            throw new RuntimeException("设备ID为空");
        }
        // 存储
        deviceData.setDeviceId(deviceId);
        deviceData.setDeviceData(s1);

        boolean save = this.save(deviceData);
        if (save) {
            return R.success().data(deviceData).code(ResultCode.SUCCESS);
        } else {
            return R.fail().code(ResultCode.UNKNOWN);
        }
    }


    /**
     * 测报灯图片
     *
     * @param
     * @return
     */
    @Override
    public R imageTelemeteringLamp(HashMap<String, Object> stringObjectHashMap) {

        // 转换成json存储
        String s = JSONObject.toJSONString(stringObjectHashMap);
        // 设默认值
        Image image = new Image();
        image.setUpdateAt(LocalDateTime.now());
        image.setCreateAt(LocalDateTime.now());
        image.setDeleteFlag(false);
        // 转换开始截取
        HashMap hashMap = JSON.parseObject(s, HashMap.class);

//       image.setResultImage(resultImage.toString());

        // 取出imei
        Object imei = hashMap.get("imei");
        image.setImei(imei.toString());
        // 根据imei查出deviceId
        Integer deviceId = deviceService.getSn(imei.toString());
        if (Objects.isNull(deviceId)) {
            throw new RuntimeException("设备ID为空");
        }
        image.setDeviceId(deviceId);

        // 判断设备是否在线 不在改为在线
        Device device = deviceService.getById(deviceId);
        if (!device.getOnline()) {
            device.setOnline(true);
            deviceService.updateById(device);
        }

        // 取出图片物种种类  若空 判断
        Object result = hashMap.get("Result");
        if (result != null) {
            image.setResult(result.toString());
        }

        // 截取图片地址
        Object images = hashMap.get("Image");

        // 存储图片并下载到指定文件夹再把路径返回给数据库
        String s1 = images.toString();
        String fileUrl = s1;   // 图片的路径
        Date date = new Date();
        String format = new SimpleDateFormat("yyyyMMdd").format(date);
        String filePath = "E:/workspace/image/" + imei.toString() + "/" + format + "/"; // 下载的路径
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";  // 具体到名字,图片
        HttpUtils.download(fileUrl, filePath, fileName);


        image.setImage(imei.toString() + "/" + format + "/" + fileName);

        // 返回图片结果给数据库
        try {
            // 返回识别图片结果
            byte[] imgData = FileUtil.readFileByBytes(filePath + fileName);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.ac2681c4f183ac86c0df7babfe7e3d65.2592000.1670984179.282335-28294342";  // AuthService生成的token值
            String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal";
            String result1 = HttpUtil.post(url, accessToken, param);
            // 拿取第一个JSON对象
            HashMap map = JSON.parseObject(result1, HashMap.class);
            Object result2 = map.get("result");
            if (result2 != null) {
                JSONArray jsonArray = JSON.parseArray(result2.toString());
                JSONObject jsonFirst = jsonArray.getJSONObject(0);
                image.setResultImage(jsonFirst.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        imageService.save(image);
        return R.success().data(image).code(ResultCode.SUCCESS);

    }

    /**
     * 孢子仪图片
     *
     * @param
     * @return
     */
    @Override
    public R imageRobeInstrument(HashMap<String, Object> stringObjectHashMap) {
        // 转换成json存储
        String s = JSONObject.toJSONString(stringObjectHashMap);

        // 设默认值
        Image image = new Image();
        image.setCreateAt(LocalDateTime.now());
        image.setUpdateAt(LocalDateTime.now());
        image.setDeleteFlag(false);
        // 准备转换提取
        HashMap hashMap = JSON.parseObject(s, HashMap.class);
        // 提取imei
        Object imei = hashMap.get("imei");
        image.setImei(imei.toString());
        // 根据imei查出deviceId
        Integer deviceId = deviceService.getSn(imei.toString());
        if (Objects.isNull(deviceId)) {
            throw new RuntimeException("设备ID为空");
        }
        image.setDeviceId(deviceId);

        // 判断设备是否在线 不在改为在线
        Device device = deviceService.getById(deviceId);
        if (!device.getOnline()) {
            device.setOnline(true);
            deviceService.updateById(device);
        }


        // 提取图片地址
        Object images = hashMap.get("Image");
        String s1 = images.toString();

        // 存入指定路径
        Date date = new Date();
        String fileUrl = s1;   // 图片
        String format = new SimpleDateFormat("yyyyMMdd").format(date);
        String filePath = "E:/workspace/image/" + imei.toString() + "/" + format + "/"; // 下载的路径
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";  // 具体到名字,图片
        HttpUtils.download(fileUrl, filePath, fileName);
        // 并存入数据库 返回指定路径
        image.setImage(imei.toString() + "/" + format + "/" + fileName);

        // 识别动物照片

        try {
            // 返回识别图片结果
            byte[] imgData = FileUtil.readFileByBytes(filePath + fileName);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.ac2681c4f183ac86c0df7babfe7e3d65.2592000.1670984179.282335-28294342";  // AuthService生成的token值
            String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal";
            String result = HttpUtil.post(url, accessToken, param);
            // 拿取第一个JSON对象
            HashMap map = JSON.parseObject(result, HashMap.class);
            Object result1 = map.get("result");
            JSONArray jsonArray = JSON.parseArray(result1.toString());
            JSONObject jsonFirst = jsonArray.getJSONObject(0);
            image.setResultImage(jsonFirst.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }


        boolean save = imageService.save(image);
        if (save) {
            return R.success().data(image).code(ResultCode.SUCCESS);
        } else {
            return R.fail().code(ResultCode.UNKNOWN);
        }

    }


    @Override
    public List<String> getByImei(Long imei) {
        return dataMapper.getPhoto(imei);

    }


//    /**
//     * 返回测报灯和孢子仪的图片
//     */
//    @Override
//    public HashMap<String, List<String>> getPhoto() {
//        HashMap<String, List<String>> hashMap = new HashMap<>();
//        // 读取文件目录名
//        String path = "D:\\data\\yf";
//        File file = new File(path);
//        String[] list = file.list();
//
//        for (int i = 0; i < list.length; i++) {
//
//            // 针对文件下目录再遍历
//            // 根据目录名查询设备类型
//            String type = deviceService.getTypeByDeviceSn(list[i]);
//            if ("3".equals(type)) {
//                List<String> stringList = new ArrayList<>();
//                // 如果是孢子仪天返回最清晰的图片
//                // File task = task();
//                // stringList.add(task.toString());
//                File test = FuzzyDetection.test(list[i]);
//                String name = test.getName();
//                name = "D:\\data\\yf\\" + list[i] + "\\" + name;
//
//                stringList.add(name);
//
//                Integer deviceId = deviceService.getSn(list[i]);
//
//                Image image = new Image();
//
//
//                image.setDeviceId(deviceId);
//                image.setImage(name);
//                image.setUpdateAt(LocalDateTime.now());
//                image.setCreateAt(LocalDateTime.now());
//                image.setDeleteFlag(false);
//                imageMapper.insert(image);
//                // image.setImage(test.toString());
//                hashMap.put(list[i], stringList);
//
//            } else {
//                List<String> stringList2 = new ArrayList<>();
//                // 如果是测报灯  读取所有的图片全部返回
//
//                String path2 = "D:\\data\\yf\\" + list[i];
//                File file2 = new File(path2);
//                String[] list2 = file2.list();
//
//                for (int j = 0; j < list2.length; j++) {
//                    String s = new String();
//                    s = path2 + "\\" + list2[j];
//                    stringList2.add(s);
//                    // image.setImage(s);
//
//                    Integer deviceId = deviceService.getSn(list[i]);
//                    Image image = new Image();
//
//                    image.setDeviceId(deviceId);
//                    image.setImage(s);
//                    image.setUpdateAt(LocalDateTime.now());
//                    image.setCreateAt(LocalDateTime.now());
//                    image.setDeleteFlag(false);
//                    imageMapper.insert(image);
//                    // imageService.save(image);
//
//
//                }
//                hashMap.put(list[i], stringList2);
//            }
//
//        }
//
//        return hashMap;
//    }


//    @Scheduled(cron = "0 0 23 * * ?")
//    public void task() {
//
//        // 读取文件目录名
//        String path = "D:\\data\\yf";
//        File file = new File(path);
//        String[] list = file.list();
//        for (int i = 0; i < list.length; i++) {
//
//            // 针对文件下目录再遍历
//            // 根据目录名查询设备类型
//            String type = deviceService.getTypeByDeviceSn(list[i]);
//            if ("3".equals(type)) {
//
//                // 如果是孢子仪天返回最清晰的图片
//                // File task = task();
//                // stringList.add(task.toString());
//                File test = FuzzyDetection.test(list[i]);
//                String name = test.getName();
//                name = "D:\\data\\yf\\" + list[i] + "\\" + name;
//                Integer deviceId = deviceService.getSn(list[i]);
//
//                Image image = new Image();
//                image.setDeviceId(deviceId);
//                image.setImage(name);
//                image.setUpdateAt(LocalDateTime.now());
//                image.setCreateAt(LocalDateTime.now());
//                image.setDeleteFlag(false);
//                imageMapper.insert(image);
//            }
//        }
//    }


    /**
     * 查询图片
     *
     * @param imei
     * @return
     */

    public static final String PATH ="D:\\workspaces\\yf\\";
    @Override
    public HashMap<Object,List<String>> findPhoto(Long imei, int page, int pageSize) {
        List<String> stringList = new ArrayList<>();
        List<String> strings =new ArrayList<>();
        HashMap<Object,List<String>> listHashMap =new HashMap<>();
        // 根据设备号查询
        String type = deviceService.getTypeByDeviceSn(String.valueOf(imei));
        if (Objects.isNull(type)) {
            throw new RuntimeException("设备id不存在");
        }
        if ("3".equals(type)) {
            // 孢子仪返回最清晰的图片,并存入数据库
            Image image = new Image();
            image.setCreateAt(LocalDateTime.now());
            image.setDeleteFlag(false);
            Integer deviceId = deviceService.getSn(String.valueOf(imei));
            image.setDeviceId(deviceId);

            File file = FuzzyDetection.test(String.valueOf(imei));
            String name = file.getName();
            name = imei + "\\" + name;
            image.setImage(name);
            stringList.add(name);


            String path =PATH+name;
            File file1 = new File(path);
            String file1Name = file1.getName();
            String suffix = file1Name.substring(file1Name.lastIndexOf(".") + 1);
            String createTime = getCreateTime(file1.getPath(), suffix);
            strings.add(createTime);

            listHashMap.put("image",stringList);
            listHashMap.put("createAt",strings);

            imageMapper.insert(image);

        } else {
            // 测报灯,全部返回,并识别结果
            try {

                String filePath = PATH+ imei;

                File file = new File(filePath);
                String[] list = file.list();
                for (int i = 0; i < list.length; i++) {
                    Image image = new Image();
                    image.setCreateAt(LocalDateTime.now());
                    image.setDeleteFlag(false);
                    Integer deviceId = deviceService.getSn(String.valueOf(imei));
                    image.setDeviceId(deviceId);


                    byte[] imgData = FileUtil.readFileByBytes(filePath + "\\" + list[i]);
                    String imgStr = Base64Util.encode(imgData);
                    String imgParam = URLEncoder.encode(imgStr, "UTF-8");

                    String param = "image=" + imgParam;

                    // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
                    String accessToken = "24.ac2681c4f183ac86c0df7babfe7e3d65.2592000.1670984179.282335-28294342";  // AuthService生成的token值
                    String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/animal";
                    String result1 = HttpUtil.post(url, accessToken, param);
                    // 拿取第一个JSON对象
                    HashMap map = JSON.parseObject(result1, HashMap.class);
                    Object result2 = map.get("result");
                    if (result2 != null) {
                        JSONArray jsonArray = JSON.parseArray(result2.toString());
                        JSONObject jsonFirst = jsonArray.getJSONObject(0);
                        image.setResultImage(jsonFirst.toString());
                    }

                    image.setImage(imei + "\\" + list[i]);

                    imageMapper.insert(image);

                    String path =PATH+imei + "\\" + list[i];
                    File file1 = new File(path);
                    String file1Name = file1.getName();
                    String suffix = file1Name.substring(file1Name.lastIndexOf(".") + 1);
                    String createTime = getCreateTime(file1.getPath(), suffix);
                    strings.add(createTime);
                    stringList.add(imei + "\\" + list[i]);
                    listHashMap.put("image",stringList);
                    listHashMap.put("createAt",strings);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return listHashMap;

    }


    public static String getCreateTime(String filePath, String suffix) {
        String strTime = null;
        try {
            Process p = Runtime.getRuntime().exec("cmd /C dir "
                    + filePath
                    + "/tc");
            InputStream is = p.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.endsWith("." + suffix)) {
                    strTime = line.substring(0, 17);
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //System.out.println("创建时间 " + strTime);
        //输出：创建时间 2009-08-17 10:21
        return strTime;
    }

}